package org.rency.common.redis.service.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.rency.common.redis.service.RedisListService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RedisListTemplateServiceImpl<K, V> extends AbstractRedisTemplate<K, V> implements RedisListService<K, V>,Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7291040053417394216L;

	private static final Logger logger = LoggerFactory.getLogger(RedisListTemplateServiceImpl.class);
	
	private final String LEFT = "Left";
	
	private final String RIGHT = "Right";

	@Override
	public long leftPush(K key, V value) {
		logger.debug("Push Queue With [{}] for {}={}.",LEFT,key,value);
		return this.getListOps().leftPush(key, value);
	}

	@Override
	public V leftPop(K key) {
		logger.debug("Pop Queue With [{}] for {}.",LEFT,key);
		return this.getListOps().leftPop(key);
	}

	@Override
	public long rightPush(K key, V value) {
		logger.debug("Push Queue With [{}] for {}={}.",RIGHT,key,value);
		return this.getListOps().rightPush(key, value);
	}

	@Override
	public V rightPop(K key) {
		logger.debug("Pop Queue With [{}] for {}.",RIGHT,key);
		return this.getListOps().rightPop(key);
	}

	@Override
	public long size(K key) {
		return this.getListOps().size(key);
	}

	@Override
	public long leftPushAll(K key, Collection<V> values) {
		return this.getListOps().leftPushAll(key, values);
	}

	@Override
	public long rightPushAll(K key, Collection<V> values) {
		return this.getListOps().rightPushAll(key, values);
	}

	@Override
	public V get(K key, long index) {
		return this.getListOps().index(key, index);
	}

	@Override
	public V rightPopAndLeftPush(K from, K to) {
		return this.getListOps().rightPopAndLeftPush(from, to);
	}

	@Override
	public long remove(K key, long index, V value) {
		return this.getListOps().remove(key, index, value);
	}

	@Override
	public void set(K key, long index, V value) {
		this.getListOps().set(key, index, value);
	}

	@Override
	public void trim(K key, long startIndex, long endIndex) {
		this.getListOps().trim(key, startIndex, endIndex);
	}

	@Override
	public long remove(K key, long startIndex, long endIndex) {
		Map<Long, V> values = new HashMap<Long, V>();
		for(long i=startIndex; i < endIndex; i++){
			V value = this.get(key, i);
			values.put(i, value);
		}
		long count = 0;
		for(Long index : values.keySet()){
			count += this.remove(key, index, values.get(index));
		}
		return count;
	}

	@Override
	public long remove(K key) {
		long length = this.size(key);
		//TODO 有待验证
		return this.remove(key, 0, length);
	}

}
